import { getTrStrategyList } from "/api/TrStrategy";

export const state = () => ({
  list: [],
  pageNum: 1,
  pageSize: 30,
  pageCount: 0,
  total: 0,
  provinceId: null,
  tagId: null,
  keywords: '',
});

export const mutations = {
  setList(state, list) {
    state.list = list;
  },
  addList(state, list) {
    state.list.push(...list); 
  },
  setPageNum(state, pageNum) {
    state.pageNum = pageNum;
  },
  setTotal(state, total) {
    state.total = total;
  },
  setPageCount(state, pageCount) {
    state.pageCount = pageCount;
  },
  setProvinceId(state, provinceId) {
    state.provinceId = provinceId;
  },
  setTagId(state, tagId) {
    state.tagId = tagId;
  },
  setKeyWords(state, keywords) {
    state.keywords = keywords;
  },
};

const getStrategy = (commit, state, pageItem) => {
  let { pageNum = 1, provinceId, tagId, keywords } = pageItem;

  // 确保 pageNum 不为负数，并且至少为 1
  pageNum = Math.max(1, pageNum);

  if (pageNum > 1 && pageNum > state.pageCount) {
    return;
  }

  if (provinceId !== state.provinceId || tagId !== state.tagId || keywords !== state.keywords) {
    pageNum = 1;
  }

  getTrStrategyList({
    pageNum,
    provinceId,
    tagId,
    keywords,
    pageSize: state.pageSize,
  }).then((data) => {
    const { code, rows, total } = data;
    if (code === 200 && rows.length > 0) {
      commit(pageNum === 1 ? 'setList' : 'addList', rows);
      commit("setPageNum", pageNum);
      commit("setTotal", total);
      commit("setPageCount", Math.ceil(total / state.pageSize)); 
      commit("setProvinceId", provinceId);
      commit("setTagId", tagId);
      commit("setKeyWords", keywords);
    }
  });
};

// export const actions = {
//   getStrategyList({ commit, state }, pageItem) {
//     getStrategy(commit, state, pageItem);
//   },
//   getNextStrategyList({ commit, state }, pageItem) {
//     pageItem.pageNum = state.pageNum + 1;
//     getStrategy(commit, state, pageItem);
//   },
// };
// export const actions = {
//   getStrategyList({ commit, state }, pageItem) {
//     console.info('Fetching Strategy List', pageItem);
//   },
//   getNextStrategyList({ commit, state }, pageItem) {
//     console.info('Fetching Next Strategy List', pageItem);
//   },
// };


export default {
	getStrategyList({ commit, state }, pageItem) {
    console.info('Fetching Strategy List', pageItem);
  },
  getNextStrategyList({ commit, state }, pageItem) {
    console.info('Fetching Next Strategy List', pageItem);
  },
}
